﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Web.Script.Serialization;
using System.Security.Cryptography;
using System.IO;
using log4net;
using PrintDemo.OtherUtil;
using PrintDemo.Forms;
using PrintDemo.DBUtil;
using PrintDemo.BLL;
using PrintDemo.Entity;
using PrintDemo.PrintHelp;
using System.Drawing.Printing;
using PrintDemo.DAL;
using Org.BouncyCastle.Ocsp;
using MySql.Data.MySqlClient;
using MySqlHelper = PrintDemo.DBUtil.MySqlHelper;
using Dapper;
using System.Management;
using System.Threading.Tasks;

namespace PrintDemo
{
    public partial class Form1 : Form
    {
        ILog _log = LogManager.GetLogger("Form1");
        private bool _needChageDb = false;
        IniConfig dbConfig = null;
        IniConfig iniConfig = null;

        OrderBLL _orderBll = new OrderBLL();
        LineTypeBLL lineTypeBLL = new LineTypeBLL();
        OperatorBLL operatorBLL = new OperatorBLL();
        ChangefulBLL changefulBLL = new ChangefulBLL();
        BoxNumBLL boxNumBLL = new BoxNumBLL();
        StackInBLL stackInBLL = new StackInBLL();
        ProductBLL productBLL = new ProductBLL();
        StackLogBLL stackLogBLL = new StackLogBLL();
        StackLocationBLL stackLocationBLL = new StackLocationBLL();

        int boxnum = 0;
        int initboxnum = 0;
        List<string> printBox = new List<string>();
        BoxNumEntity printEntity = null;
        string PrinterName = "";

        int boxNumLength = 0;

        public Form1()
        {
            InitializeComponent();
            dbConfig = new IniConfig("DbSetting.ini");
            iniConfig = new IniConfig("printer_config.ini");
            _needChageDb = IsKeyPushedDown(Keys.ShiftKey);
            if (_needChageDb)
            {
                _needChageDb = false;
                //DBConnSetting set = RegistryUtil.GetDbConfig();
                DBConnSetting set = GetDbConfig();
                OpenSettingForm(set);
            }
            int oneBoxCount = Convert.ToInt32(numOneBoxCount.Value);
            int boxCount = Convert.ToInt32((int)numBoxCount.Value);
            this.txtAllBoxCount.Text = (oneBoxCount * boxCount).ToString();
        }

        public void SerPrinter()
        {
            PrintDialog print = new PrintDialog();
            print.AllowCurrentPage = true;
            print.AllowPrintToFile = true;
            print.AllowSelection = true;
            print.AllowSomePages = true;
            print.ShowHelp = true;
            if (print.ShowDialog() == DialogResult.OK)
            {
                string PrinterName = print.PrinterSettings.PrinterName;
                iniConfig.Write("PrinterName", PrinterName, "BoxPrinter");
            }
            else
                return;
        }

        public bool IsExist()
        {
            var flag = iniConfig.KeyExists("PrinterName", "BoxPrinter");
            if (!flag)
                return false;
            PrinterName = iniConfig.Read("PrinterName", "BoxPrinter");
            return true;
        }

        /// <summary>
        /// 初始化箱号长度
        /// </summary>
        public void InitBoxNumLength()
        {
            var flag = iniConfig.KeyExists("BoxNumLength", "BoxPrinter");
            if (flag)
            {
                boxNumLength = Convert.ToInt32(iniConfig.Read("BoxNumLength", "BoxPrinter"));
            }
            else
            {
                iniConfig.Write("BoxNumLength", 6.ToString(), "BoxPrinter");
                boxNumLength = 6;
            }

        }
        private void OpenSettingForm(DBConnSetting set)
        {
            DBSettingForm dbForm = new DBSettingForm(set);
            dbForm.StartPosition = FormStartPosition.CenterScreen;
            dbForm.SaveConfigHandler += DbForm_SaveConfigHandler;
            dbForm.TopMost = true;
            dbForm.ShowDialog();
            dbForm.BringToFront();
        }
        private void DbForm_SaveConfigHandler(bool success)
        {
            if (!success)
            {
                MessageBox.Show("保存数据库设置失败！程序将退出。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }
        }
        private DBConnSetting GetDbConfig()
        {
            DBConnSetting set = new DBConnSetting();
            try
            {
                var flag = dbConfig.KeyExists("Server", "MySQLSetting");
                if (!flag)
                    return null;
                flag = dbConfig.KeyExists("DbName", "MySQLSetting");
                if (!flag)
                    return null;
                flag = dbConfig.KeyExists("User", "MySQLSetting");
                if (!flag)
                    return null;
                flag = dbConfig.KeyExists("Psw", "MySQLSetting");
                if (!flag)
                    return null;
                set.Server = dbConfig.Read("Server", "MySQLSetting");
                set.DbName = dbConfig.Read("DbName", "MySQLSetting");
                string user = dbConfig.Read("User", "MySQLSetting");
                if (user != string.Empty)
                    set.User = Base64Util.Base64Decode(Encoding.UTF8, user);//DataProtector.DecryptLocalMachine(user, DataProtector.SALT);
                string psw = dbConfig.Read("Psw", "MySQLSetting");
                if (psw != string.Empty)
                    set.Psw = Base64Util.Base64Decode(Encoding.UTF8, psw);//DataProtector.DecryptLocalMachine(psw, DataProtector.SALT);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            return set;
        }

        public string DESEnCode(string pToEncrypt, string sKey)
        {
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.GetEncoding("UTF-8").GetBytes(pToEncrypt);
            des.Key = Encoding.ASCII.GetBytes(sKey);
            des.IV = Encoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            byte[] array = ms.ToArray();
            for (int i = 0; i < array.Length - 1; i++)
            {
                byte b = array[i];
                ret.AppendFormat("{0:X2}", b);
            }
            return ret.ToString();
        }
        public static bool IsKeyPushedDown(System.Windows.Forms.Keys vKey)
        {
            return 0 != (Win32Helper.GetAsyncKeyState((int)vKey) & 0x8000);
        }


        private void btnPrint_Click(object sender, EventArgs e)
        {
            try
            {
                //_log.Info("获取COM实例");
                //m2 a3 = (m2)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("1A1C4414-8F4A-48D8-B264-9764819046F1")));
                //_log.Info("创建House实例");
                //House house = new House();
                //house.c1 = "N-FF13A204A";//产品名称
                //house.k1 = "F2 FLOOR";//库位
                //house.p1 = "";
                //house.s1 = "100";//整箱数量
                //house.x1 = "2023216527";//箱号
                //var javaScriptSerializer = new JavaScriptSerializer();
                //_log.Info("开始序列化house");
                //string m3 = javaScriptSerializer.Serialize(house);
                //_log.Info("进行DESEnCode");
                //m3 = DESEnCode(m3, "12345678");
                //_log.Info("进行showm2");
                //a3.showm2("N-FF13A204A", "2023216527", "MO2305110003", "Lv018460", "10", "JuanHao", "6.34", "HYP", m3);
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }




            //LGApp objApp = new LGApp();     //实例化读取标签的对象
            ////LGLabel ObjLabel = objApp.LabelOpenEx(@"D:\文档\地区\Setup1\cpbq.lbl");   //读取标签
            ////MessageBox.Show("测试程序!", "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            //int PrintQty = 0;
            //try
            //{
            //    //PrintQty = int.Parse(txtQuantity.Text);  
            //}
            //catch {
            //    PrintQty = 0;
            //}

            //if (PrintQty > 0)
            //{
            //    //ObjLabel.Print(txtQuantity.Text);  //打印  传入打印的数量
            //    objApp.LabelClose(0);                //关闭引用
            //}
        }


        public void InitPrintSerach()
        {
            Task.Run(() => {
                string query = string.Format("select * from Win32_Printer where Name = '{0}'", PrinterName);
                var searcher = new ManagementObjectSearcher(query);
                var printers = searcher.Get();
            });
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            InitPrintSerach();
            DBConnSetting set = GetDbConfig();
            if (!ValidDbSettingRule.ValidDBSetting(set))
            {
                OpenSettingForm(set);
            }
            //iniConfig = new IniConfig("printer_config.ini");
            InitBoxNumLength();
            #region 下拉框初始化
            cmbLineType.DisplayMember = "LineTypeName";
            cmbLineType.ValueMember = "LineTypeName";
            cmbOperator.DisplayMember = "OperatorName";
            cmbOperator.ValueMember = "OperatorName";
            //线型数据源配置
            var linetype = lineTypeBLL.GetList().ToList();
            cmbLineType.DataSource = linetype;
            //操作员数据源配置
            var operatorEx = operatorBLL.GetList().ToList();
            cmbOperator.DataSource = operatorEx;

            var list1 = stackLocationBLL.GetList().OrderBy(x => x.CreateTime).ToList().Select(x => x.StackName).ToArray();
            this.txtStore.Items.AddRange(list1);
            if(list1 != null && list1.Count() > 0)
                this.txtStore.SelectedIndex = 0;

            this.cmbMaoYiType.SelectedIndex= 0;
            #endregion

            var changeEntity = changefulBLL.GetList().ToList();
            if (changeEntity != null && changeEntity.Count == 1)
            {
                var curboxnum = changeEntity[0].BoxNum + 1;
                var len = curboxnum.ToString().Length;
                string zero = "";
                for (int i = len; i < boxNumLength; i++)
                {
                    zero += "0";
                }
                var res = zero.ToString() + curboxnum.ToString();
                this.txtBoxNum.Text = DateTime.Now.Year.ToString() + res;
            }
            var list = _orderBll.GetList().OrderByDescending(x => x.OrderId).Take(100).ToList().Select(x => x.OrderId).ToArray();
            this.cmbOrderId.Items.AddRange(list);
        }

        private void numOneBoxCount_ValueChanged(object sender, EventArgs e)
        {
            int oneBoxCount = Convert.ToInt32(numOneBoxCount.Value);
            int boxCount = Convert.ToInt32((int)numBoxCount.Value);
            this.txtAllBoxCount.Text = (oneBoxCount * boxCount).ToString();
        }

        private void numBoxCount_ValueChanged(object sender, EventArgs e)
        {
            Computer();
        }
        private void Computer()
        {
            boxnum = initboxnum;
            int oneBoxCount = Convert.ToInt32(numOneBoxCount.Value);
            int boxCount = Convert.ToInt32((int)numBoxCount.Value);
            this.txtAllBoxCount.Text = (oneBoxCount * boxCount).ToString();
        }

        private void cmbOrderId_SelectedIndexChanged(object sender, EventArgs e)
        {
            ChangeValue();
        }

        private void cmbOrderId_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                ChangeValue();
            }
        }
        public void ChangeValue()
        {
            if (!string.IsNullOrEmpty(cmbOrderId.Text))
            {
                var list = _orderBll.GetListByWhere(cmbOrderId.Text).ToList();
                if (list == null || list.Count < 1)
                {
                    MessageBox.Show("该制令单号不存在!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                OrderEntity orderEntity = list[0];
                this.txtBatch.Text = orderEntity.Batch;
                this.txtFinishedProductName.Text = orderEntity.FinishedProductName;
                this.cmbLineType.Text = orderEntity.LineType;
                this.txtJuanNum.Text = orderEntity.JuanNum;
                this.cmbOperator.Text = orderEntity.Operator;
            }
        }

        public bool IsValid()
        {
            errorProvider1.Clear();
            bool res = true;

            if (string.IsNullOrEmpty(cmbOrderId.Text.Trim()))
            {
                res = false;
                errorProvider1.SetError(cmbOrderId, "制令单号不能为空！");
            }
            else if (string.IsNullOrEmpty(txtFinishedProductName.Text.Trim()))
            {
                res = false;
                errorProvider1.SetError(txtFinishedProductName, "成品名称不能为空！");
            }
            else if (string.IsNullOrEmpty(txtBatch.Text.Trim()))
            {
                res = false;
                errorProvider1.SetError(txtBatch, "批号不能为空！");
            }
            else if (string.IsNullOrEmpty(cmbLineType.Text))
            {
                res = false;
                errorProvider1.SetError(cmbLineType, "线型不能为空！");
            }
            else if (string.IsNullOrEmpty(txtJuanNum.Text))
            {
                res = false;
                errorProvider1.SetError(txtJuanNum, "卷号不能为空！");
            }
            else if (string.IsNullOrEmpty(txtStore.Text))
            {
                res = false;
                errorProvider1.SetError(txtStore, "库位不能为空！");
            }
            else if (string.IsNullOrEmpty(txtBoxNum.Text))
            {
                res = false;
                errorProvider1.SetError(txtBoxNum, "箱号不能为空！");
            }
            //else if (!numBoxCount.Value.ToString().Contains("至"))
            //{
            //    res = false;
            //    errorProvider1.SetError(numBoxCount, "需修改箱号！");
            //}
            return res;
        }

        public BoxNumEntity GetEntity()
        {
            BoxNumEntity boxNumEntity = new BoxNumEntity();
            boxNumEntity.Id = Guid.NewGuid().ToString();
            boxNumEntity.OrderId = cmbOrderId.Text;
            boxNumEntity.Batch = txtBatch.Text;
            boxNumEntity.Operator = cmbOperator.Text;
            boxNumEntity.FinishedProductName = txtFinishedProductName.Text;
            boxNumEntity.CreateTime = DateTime.Now;
            boxNumEntity.LineType = cmbLineType.Text;
            boxNumEntity.JuanNum = txtJuanNum.Text;
            boxNumEntity.MaoZhong = numMaoZhong.Value.ToString();
            boxNumEntity.OneBoxCount = Convert.ToInt32(numOneBoxCount.Value);
            boxNumEntity.Store = txtStore.Text;
            boxNumEntity.AllCount = Convert.ToInt32(txtAllBoxCount.Text);
            boxNumEntity.BoxNum = txtBoxNum.Text;
            return boxNumEntity;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (dbConfig != null)
            {
                dbConfig.Dispose();
                dbConfig = null;
            }
            if (iniConfig != null)
            {
                iniConfig.Dispose();
                iniConfig = null;
            }
        }

        private void btnSaveAndPrint_Click(object sender, EventArgs e)
        {
            this.btnSaveAndPrint.Enabled = false;
            if (!IsExist())
            {
                if (MessageBox.Show("请先配置打印机", "是否配置", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    SerPrinter();
                    if (!iniConfig.KeyExists("PrinterName", "BoxPrinter") || string.IsNullOrEmpty(iniConfig.Read("PrinterName", "BoxPrinter")))
                    {
                        this.btnSaveAndPrint.Enabled = true;
                        return;
                    }
                    else
                        PrinterName = iniConfig.Read("PrinterName", "BoxPrinter");
                }
                else
                {
                    this.btnSaveAndPrint.Enabled = true;
                    return;
                }
            }
            //PrinterHelper.printerName = PrinterName;
            //var ee = PrinterHelper.GetPrinterStatusCodeInt2();
            //var aa = PrinterHelper.GetPrinterStatusCodeInt();
            //var bb = PrinterHelper.CheckIsEnable(aa);
            //var cc = PrinterHelper.GetPrinterStatusMessage(aa);
            //var dd = PrinterHelper.GetTaskNumber();
            //if()
            string query = string.Format("select * from Win32_Printer where Name = '{0}'",PrinterName);
            var searcher = new ManagementObjectSearcher(query);
            var printers = searcher.Get();
            bool isExistPrint = false;
            foreach (var printer in printers)
            {
                if (printer.Properties["Name"].Value.ToString() == PrinterName)
                {
                    isExistPrint = true;
                    if (Convert.ToBoolean(printer.Properties["WorkOffline"].Value))
                    {
                        MessageBox.Show(string.Format("打印机{0}处于离线状态，请开启或更换打印机。", PrinterName), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        this.btnSaveAndPrint.Enabled = true;
                        return;
                    }
                }
                //显示部分属性
                //Console.WriteLine(printer.Properties["Name"].Value);                    //获取打印机名称
                //Console.WriteLine(printer.Properties["PortName"].Value);                //获取打印机端口号
                //Console.WriteLine(printer.Properties["Default"].Value);                 //获取打印机是否是默认打印机
                //Console.WriteLine(printer.Properties["PrinterStatus"].Value);           //获取打印机工作状态
                //Console.WriteLine(printer.Properties["WorkOffline"].Value);             //获取打印机是否离线

            }

            if (!isExistPrint)
            {
                MessageBox.Show(string.Format("当前系统中不存在打印机{0}。", PrinterName), "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.btnSaveAndPrint.Enabled = true;
                return;
            }

            if (!IsValid())
            {
                this.btnSaveAndPrint.Enabled = true;
                return;
            }
            var list = _orderBll.GetListByWhere(cmbOrderId.Text).ToList();
            if (list == null || list.Count < 1)
            {
                MessageBox.Show("该制令单号不存在!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                this.btnSaveAndPrint.Enabled = true;
                return;
            }
            var entity = GetEntity();
            printEntity = GetEntity();

            #region 生成箱号列表
            var boxCount = Convert.ToInt32(numBoxCount.Value);  //总箱数
            var begin = Convert.ToInt32(entity.BoxNum.Substring(4));
            if (boxCount != 1)
            {
                for (int i = 0; i < boxCount; i++)
                {
                    var len = begin.ToString().Length;
                    string zero = "";
                    for (int j = len; j < boxNumLength; j++)
                    {
                        zero += "0";
                    }
                    var res = zero.ToString() + begin.ToString();
                    printBox.Add(DateTime.Now.Year.ToString() + res.ToString());   //保存箱号到List
                    begin++;
                }
            }
            else
            {
                printBox.Add(entity.BoxNum);
            }
            #endregion

            Print();
        }

        public void Print()
        {
            try
            {
                #region 老版32位打印
                //m2 a3 = (m2)Activator.CreateInstance(Type.GetTypeFromCLSID(new Guid("1A1C4414-8F4A-48D8-B264-9764819046F1")));
                //foreach (var item in printBox)
                //{
                //    House house = new House();
                //    house.c1 = printEntity.FinishedProductName;//产品名称
                //    house.k1 = printEntity.Store;//库位
                //    house.p1 = "";
                //    house.s1 = printEntity.OneBoxCount.ToString();//整箱数量
                //    house.x1 = item;//箱号
                //    var javaScriptSerializer = new JavaScriptSerializer();
                //    string m3 = javaScriptSerializer.Serialize(house);
                //    m3 = DESEnCode(m3, "12345678");
                //    a3.showm2(printEntity.FinishedProductName, item, printEntity.OrderId, printEntity.Batch, printEntity.AllCount.ToString(), printEntity.JuanNum, printEntity.MaoZhong, printEntity.Operator, m3);
                //}
                #endregion

                PrintHelper printHelp = new PrintHelper(printBox, printEntity, PrinterName, boxNumLength, new Action(SetButtonStauts),new Action<string>(SetNewBoxNum));
                printHelp.PrintBox();
            }
            catch (Exception ex)
            {
                _log.Error(ex.Message);
            }
        }

        public void SetButtonStauts()
        {
            this.BeginInvoke(new MethodInvoker(delegate
            {
                this.btnSaveAndPrint.Enabled = true;
            }));
        }

        //更新页面的箱号
        public void SetNewBoxNum(string newBoxNum)
        {
            this.BeginInvoke(new MethodInvoker(delegate
            {
                this.txtBoxNum.Text = newBoxNum;
            }));
        }
    }
    public class House
    {
        public string x1 { get; set; }
        public string p1 { get; set; }
        public string s1 { get; set; }
        public string k1 { get; set; }
        public string c1 { get; set; }

    }
}
